package main

import (
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"net/http"
)

func main() {

	//Default返回一个默认的路由引擎
	r := gin.Default()

	// GET	获取querystring参数	http://127.0.0.1:8080/user/search?username=Benjamin&address=gold
	r.GET("/user/search", func(c *gin.Context) {

		//username := c.Query("username")
		username := c.DefaultQuery("username", "小王子")
		address := c.Query("address")

		//输出json结果给调用方
		c.JSON(http.StatusOK, gin.H{
			"message":  "ok",
			"method":   "GET",
			"username": username,
			"address":  address,
		})
	})

	// GET	获取path参数	http://127.0.0.1:8080/user/search/小王子/沙河
	r.GET("/user/search/:username/:address", func(c *gin.Context) {
		username := c.Param("username")
		address := c.Param("address")
		//输出json结果给调用方
		c.JSON(http.StatusOK, gin.H{
			"message":  "ok",
			"username": username,
			"address":  address,
		})
	})

	// POST	获取form参数	http://127.0.0.1:8080/user/search
	r.POST("/user/search", func(c *gin.Context) {

		// DefaultPostForm取不到值时会返回指定的默认值
		username := c.DefaultPostForm("username", "未知")
		//username := c.PostForm("username")
		address := c.PostForm("address")

		//输出json结果给调用方
		c.JSON(http.StatusOK, gin.H{
			"message":  "ok",
			"method":   "POST",
			"username": username,
			"address":  address,
		})
	})

	// POST	获取json参数	http://127.0.0.1:8080/json
	r.POST("/json", func(c *gin.Context) {

		// 获取请求参数，并返回请求参数
		// 注意：下面为了举例子方便，暂时忽略了错误处理
		b, _ := c.GetRawData() // 从c.Request.Body读取请求数据

		// 定义map或结构体
		var m map[string]interface{}
		// 反序列化
		_ = json.Unmarshal(b, &m)

		c.JSON(http.StatusOK, m)

	})

	r.Run()

}
